package com.ocom.payhandle.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.ocom.common.entity.card.EntityXfGoodListOrg;
import com.ocom.common.entity.card.EntityXfGoodsListProcess;
import com.ocom.common.entity.card.EntityXfRecordProcess;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.JsonUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.devicehttp.MachMealDataVo;
import com.ocom.common.vo.payconfig.kitchenprinter.GoodsListProcessDishesDto;
import com.ocom.common.vo.pyhandle.OrderMealListVo;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payhandle.dao.IDaoXfGoodsListProcess;
import com.ocom.payhandle.feign.XfRecordFeign;
import com.ocom.payhandle.service.XfGoodsListProcessService;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;



@Slf4j
@Service
public class XfGoodsListProcessServiceImpl extends ServiceImpl<IDaoXfGoodsListProcess, EntityXfGoodsListProcess> implements XfGoodsListProcessService {


    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private IDaoXfGoodsListProcess iDaoXfGoodsListProcess;
    @Autowired
    private XfRecordFeign xfRecordFeign;


    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.MASTER)
    public Boolean addXfGoodsListProcessList(Long companyId, List<EntityXfGoodsListProcess> list) {
        try {
            String toJson = JsonUtils.toJson(list);
            redisUtil.set("redisOrder:" + companyId + ":" + list.get(0).getOrderNo() + ":GOOD", toJson, 500l);
        } catch (Exception e) {
            log.info("添加菜品redis缓存异常 FrKin07N4N 【{}】【{}】", list, e);
        }
        return  this.saveBatch(list);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityXfGoodsListProcess> getXfGoodsList(Long companyId,String orderNo) {
        if(CommonUtil.isNull(orderNo)) return  new ArrayList<>();
        List<EntityXfGoodsListProcess> listProcesses =new ArrayList<>();
        try {
            listProcesses = JsonUtils.fromJson((String) redisUtil.get("redisOrder:" + companyId
                    + ":" + orderNo + ":GOOD"), new TypeReference<List<EntityXfGoodsListProcess>>() {});
        }catch (Exception e){
            log.info("查询redis缓存异常 spAspJxG7G 【{}】【{}】", orderNo, e);
        }
        if (listProcesses == null ||  listProcesses.size() <= 0) {
            QueryWrapper<EntityXfGoodsListProcess> queryWrapper =new QueryWrapper<>();
            queryWrapper.eq("com_id",companyId);
            queryWrapper.eq("order_no",orderNo);
            listProcesses = this.list(queryWrapper);
        }
        return  listProcesses;
    }

    @Override
    @DataSourceAspect(companyId = "comId", type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<GoodsListProcessDishesDto> getGoodsListProcessOnDishes(Long comId, String orderNo){
        return iDaoXfGoodsListProcess.getGoodsListProcessOnDishes(comId, orderNo);
    }
    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.MASTER)
    public Boolean saveXfGoodsList(Long companyId, EntityXfRecordProcess entityXfRecordProcess, List<MachMealDataVo> mealData) {
        //2023年9月18日14:19:57 菜品缓存表
        try {
            if (mealData != null && mealData.size() > 0) {
                List<EntityXfGoodsListProcess> entityXfGoodsListProcesses = new ArrayList<>();
                if(entityXfRecordProcess.getMerchId()==null)  entityXfRecordProcess.setMerchId(0l);
                if(entityXfRecordProcess.getDeptId()==null)  entityXfRecordProcess.setDeptId(0l);
                if(entityXfRecordProcess.getPId()==null)  entityXfRecordProcess.setPId(0l);
                for (MachMealDataVo menuDataVo:mealData) {
                    EntityXfGoodsListProcess entityXfGoodsListProcess =new EntityXfGoodsListProcess();
                    entityXfGoodsListProcess.setComId(companyId);
                    entityXfGoodsListProcess.setDeviceNo(entityXfRecordProcess.getDeviceNo());
                    entityXfGoodsListProcess.setPointId(entityXfRecordProcess.getPointId().intValue());
                    entityXfGoodsListProcess.setMerchId(entityXfRecordProcess.getMerchId().intValue());
                    entityXfGoodsListProcess.setPId(entityXfRecordProcess.getPId().longValue());
                    entityXfGoodsListProcess.setDeptId(entityXfRecordProcess.getDeptId().intValue());
                    entityXfGoodsListProcess.setReceiptId(0);
                    entityXfGoodsListProcess.setReceiptName("");
                    entityXfGoodsListProcess.setOrderNo(entityXfRecordProcess.getOrderNo());
                    entityXfGoodsListProcess.setConsTime(entityXfRecordProcess.getConsTime());
                    entityXfGoodsListProcess.setMealDate(entityXfRecordProcess.getMealDate());
                    entityXfGoodsListProcess.setMealNo(entityXfGoodsListProcess.getMealNo());
                    entityXfGoodsListProcess.setConsType(entityXfRecordProcess.getConsType());
                    entityXfGoodsListProcess.setIfRefund(0);
                    entityXfGoodsListProcess.setDishesId(menuDataVo.getDishesId());
                    entityXfGoodsListProcess.setDishesName(menuDataVo.getDishesName());
                    entityXfGoodsListProcess.setPriceMode(menuDataVo.getPriceMode());
                    entityXfGoodsListProcess.setWeightNumber(menuDataVo.getNum());
                    entityXfGoodsListProcess.setDishesPrice(menuDataVo.getPrice());
                    entityXfGoodsListProcess.setUnitPrice(menuDataVo.getUnitPrice());
                    entityXfGoodsListProcess.setMonthValue(entityXfRecordProcess.getMonthValue());
                    entityXfGoodsListProcess.setCreateTime(new Date());
                    entityXfGoodsListProcesses.add(entityXfGoodsListProcess);
                }

                String toJson = JsonUtils.toJson(entityXfGoodsListProcesses);
                redisUtil.set("redisOrder:" + entityXfRecordProcess.getComId()
                        + ":" + entityXfRecordProcess.getOrderNo() + ":GOOD", toJson, 500l);

                return  this.saveBatch(entityXfGoodsListProcesses);
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式:【{}】,机器号:【{}】,入库菜品缓存表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存消费记录）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
            log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存消费记录）", entityXfRecordProcess.getDeviceNo(), mealData, ResultUtil.error(ResultEnum.Err_900));
            return false;
        }
        return true;
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    public Boolean saveXfGoodsListRecode(Long companyId, String orderNo) {
        try {
            List<EntityXfGoodsListProcess> listProcesses =new ArrayList<>();
            try {
                listProcesses = JsonUtils.fromJson((String) redisUtil.get("redisOrder:" + companyId
                        + ":" + orderNo + ":GOOD"), new TypeReference<List<EntityXfGoodsListProcess>>() {});
            }catch (Exception e){
                log.info("查询redis缓存异常 spAspJxG7G 【{}】【{}】", orderNo, e);
            }
            if (listProcesses == null ||  listProcesses.size() <= 0) {
                QueryWrapper<EntityXfGoodsListProcess> queryWrapper =new QueryWrapper<>();
                queryWrapper.eq("com_id",companyId);
                queryWrapper.eq("order_no",orderNo);
                listProcesses = this.list(queryWrapper);
            }

            if (listProcesses != null && listProcesses.size() > 0) {
                List<EntityXfGoodListOrg> listOrgs = JSON.parseArray(JSON.toJSONString(listProcesses), EntityXfGoodListOrg.class);
                xfRecordFeign.saveXfGoodListBatch(listOrgs);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("消息-迁移订单详情表处理失败:【{}】", e);
        }
        return true;
    }


    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<OrderMealListVo> getOrderListByMeal(Long companyId,
                                                    Long pId,
                                                    String mealDate,
                                                    Integer mealNo) {
        return iDaoXfGoodsListProcess.getOrderListByMeal(companyId,
                pId,
                mealDate,
                mealNo
        );
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.MASTER)
    public Boolean xfGoodsListRrfund(Long companyId, String orderNo) {
        redisUtil.del("redisOrder:" + companyId + ":" + orderNo + ":GOOD");
        UpdateWrapper<EntityXfGoodsListProcess> updateWrapper =new UpdateWrapper<>();
        updateWrapper.eq("com_id",companyId);
        updateWrapper.eq("order_no",orderNo);
        updateWrapper.set("if_refund",1);
        return  this.update(updateWrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.MASTER)
    public Boolean xfGoodsListRrfund(Long companyId, String orderNo,Integer dishId) {
        redisUtil.del("redisOrder:" + companyId + ":" + orderNo + ":"+dishId+":GOOD");
        UpdateWrapper<EntityXfGoodsListProcess> updateWrapper =new UpdateWrapper<>();
        updateWrapper.eq("com_id",companyId);
        updateWrapper.eq("order_no",orderNo);
        updateWrapper.eq("dishes_id",dishId);
        updateWrapper.set("if_refund",1);
        return  this.update(updateWrapper);
    }


    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityXfGoodsListProcess> getUserMeal(Long companyId,Integer pointId, Long pId,String mealDate, Integer mealNo) {
        QueryWrapper<EntityXfGoodsListProcess> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("com_id",companyId);
        queryWrapper.eq("point_id",pointId);
        queryWrapper.eq("p_id",pId);
        queryWrapper.eq("meal_date",mealDate);
        queryWrapper.eq("meal_no",mealNo);
        queryWrapper.eq("if_refund",0);
        queryWrapper.orderByDesc("create_time");
        return  this.list(queryWrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    public EntityXfGoodsListProcess getXfGoodsList(Long companyId, String orderNo, Integer dishsId) {
        return this.getOne(Wrappers.lambdaQuery(EntityXfGoodsListProcess.class).eq(EntityXfGoodsListProcess::getComId,companyId).eq(EntityXfGoodsListProcess::getOrderNo,orderNo).eq(EntityXfGoodsListProcess::getDishesId,dishsId).last("limit 1"));
    }
}
